
#用于语音识别和TTS

import setting
import os
from voicetools import BaiduVoice

token=BaiduVoice.get_baidu_token(setting.BAIDU_VOICE_API_KEY,setting.BAIDU_VOICE_SECRET_KEY)
bv = BaiduVoice(token['access_token'])

#聆听，返回字符串
def listenWords():
    try:
        os.system('arecord -D "plughw:CARD=Device" -f S16_LE -d 4 /tmp/voice.wav')
        result = bv.asr("/tmp/voice.wav")
        return result[0]
    except Exception as e:
        return None

#聆听语音指令，返回命令词组
def listen():
    words = listenWords()
    if words == None:
        return words
    else:
        result = []
        #简单的命令识别
        if words.find("天气")>=0:
            result.append("weather")
        if words.find("空气")>=0:
            result.append("pm25")
        if (words.find("家里")>=0 or words.find("室内")>=0 or words.find("屋里")>=0) and (words.find("温度")>=0 or words.find("湿度")>=0):
            result.append("houseWeather")
        if words.find("舞")>=0:
            result.append("dance")
    return result

#说话 成功返回True 否则返回False
def talk(words):
    for i in range(setting.MAX_REQUEST_TIME):
        try:
            result = bv.tts(words)
            with open('/tmp/talk.mp3', 'wb') as f:
                f.write(result)
            os.system('mpg123 -a "plughw:CARD=Device" /tmp/talk.mp3')
            return True
        except Exception as e:
            continue
    return False
